import os
import subprocess
import csv
from datetime import datetime

# Configuration
script_dir = os.path.dirname(os.path.abspath(__file__))
base_dir = os.path.join(script_dir, '..')
my_gossip_path = os.path.join(base_dir, 'target', 'debug', 'my-gossip.exe')
results_dir = os.path.join(base_dir, 'results', 'logs')
os.makedirs(results_dir, exist_ok=True)


def build_executable():
    """Function to build the executable"""
    subprocess.run(
        f"pushd {base_dir} && cargo build && popd", shell=True, check=True)


def run_experiment(node_num, k_value):
    """Function to run the experiment"""
    try:
        result = subprocess.run(
            f"{my_gossip_path} -n {node_num} -k {k_value}", stdout=subprocess.PIPE, shell=True, text=True, check=True)
        output_lines = result.stdout.strip().split('\n')
        for line in output_lines:
            if line.startswith("Result >>>>"):
                parts = line[len("Result >>>>"):].replace(
                    ',', '').strip().split()
                error = float(parts[0])
                rounds = int(parts[1])
                return error, rounds
    except subprocess.CalledProcessError as e:
        print(
            f"Error running experiment with node {node_num} and k {k_value}: {e}")
    return float("nan"), float("nan")


def save_results_to_csv(results, filename):
    """Function to save results to a CSV file"""
    with open(filename, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
        writer.writerow(['Node', 'K', 'Error', 'Rounds'])
        for result in results:
            writer.writerow(result)


# Experiment parameters
node_nums = list(range(3, 30))
k_values = list(range(2, 10))
trials = 10

# Build the executable before running experiments
build_executable()

# Run experiments and collect results
results = []
for node in node_nums:
    for k in k_values:
        for _ in range(trials):
            error, rounds = run_experiment(node, k)
            results.append((node, k, error, rounds))

# Save results to a CSV file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = os.path.join(results_dir, f'raw_results_{timestamp}.csv')
save_results_to_csv(results, filename)
print(f"Results have been saved to {filename}")
